package org.dandsoft.blackbox.laboratory.tools;

import org.apache.jackrabbit.core.TransientRepository;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.jackrabbit.core.config.ConfigurationException;

import javax.jcr.*;
import java.io.InputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Hashtable;

/**
 * Created by IntelliJ IDEA.
 * User: dvilyuzhanin
 * Date: 29.03.2009 1:23:01
 */
public class JCRRepositorySingelton {
    private static JCRRepositorySingelton instance = new JCRRepositorySingelton();

    private Map<String, Repository> repositories = new Hashtable<String, Repository>();

    public void open(String workDir) {
        try {
            Repository repository = repositories.get(workDir);
            if (repository == null) {
                InputStream in = getClass().getClassLoader().getResourceAsStream("repository.xml");
                repository = new TransientRepository(RepositoryConfig.create(in, workDir));
                repositories.put(workDir, repository);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ConfigurationException e) {
            throw new RuntimeException(e);
        }
    }

    public Session getSession(String workDir) {
        try {
            Credentials credentials = new SimpleCredentials("admin", "".toCharArray());
            Repository repository = repositories.get(workDir);
            if (repository == null) {
                open(workDir);
                return repositories.get(workDir).login(credentials);
            } else {
                return null;
            }
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }

    }

    public Session getSession(String workspace, String workDir) {
        try {
            Credentials credentials = new SimpleCredentials("admin", "".toCharArray());
            Repository repository = repositories.get(workDir);

            if (repository == null) {
                open(workDir);
                Session session = repositories.get(workDir).login(credentials, workspace);
                return session;
            } else {
                return null;
            }
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    public static JCRRepositorySingelton getInstance() {
        return instance;
    }
}
